package com.atguigu.gulimall.order.interceptor;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.constant.OrderConstant;
import com.atguigu.common.vo.MemberRespVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
@Slf4j
public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberRespVo> loginUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        /**
         * 解锁库存需要查询订单信息，防止被拦截，需要直接放行
         *
         * @see com.sherlock.gmall.ware.rabbitListener.ReleaseLockStock#handStockLockedRelease(com.sherlock.common.to.mq.StockLockedTo, org.springframework.amqp.core.Message, com.rabbitmq.client.Channel)
         */
        StringBuffer requestURL = request.getRequestURL();
        log.info("request Url is {}", requestURL);

        // 远程调用本系统的系统，只要进行的Feign的配置，就会携带请求的session信息，可以获取到登录信息，则这块不需要过滤任何请求, 但是这个请求是gmall-ware的MQ发的，所以还是需要直接过滤掉，不要拦截
        // 查询订单信息， 主要是为了查询订单此时的状态
        for (String whiteUrl : OrderConstant.ORDER_REQUEST_WHITE_LIST) {
            if(new AntPathMatcher().match(whiteUrl, requestURL.toString())){
                return true;
            }
        }

        HttpSession session = request.getSession();
        MemberRespVo member = (MemberRespVo) session.getAttribute(AuthServerConstant.GULIMALL_LOGIN_USER);
        if(member != null){
            loginUser.set(member);
            return true;
        }else{
            session.setAttribute("msg","请先登录");
            response.sendRedirect("http://auth.gulimall.com");
            return false;
        }
    }
}
